<template>
    <div>
        <div class="system-title">VUE3+TS+Vite+Pinia+Element / Ant Design </div>

        <div class="login-content">
            <div class="login-title">
                <h2>用户登录</h2>
            </div>
            <el-form ref="ruleFormRef" :model="state.formData" status-icon :rules="formRules" label-width="0px"
                class="demo-formData">
                <el-form-item label="" prop="username" style="margin-bottom: 40px">
                    <el-input v-model="state.formData.username" placeholder="账号： wmin" />
                </el-form-item>
                <el-form-item label="" prop="password" style="margin-bottom: 40px">
                    <el-input placeholder="密码： 123456" v-model="state.formData.password" type="password"
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="" prop="code" style="margin-bottom: 40px">
                    <el-input class="codeInput" v-model="state.formData.code" placeholder="输入验证码" clearable
                        maxlength="4" />
                    <!-- <slideVerify class="codeShow" v-model:identifyCode="identifyCode" @click="refresh()"></slideVerify> -->
                </el-form-item>
                <el-form-item>
                    <div class="btn-content">
                        <label class="labelText">
                            <input type="checkbox" v-model="rem_pswd" /> 记住密码
                        </label>
                        <div class="btn">
                            <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="state.loading">登录</el-button>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
// 导入登录 API 方法
// import {UseLoginApi} from "@/api/login/index"
// 导入登录状态的类型
import { LoginState } from "@/api/login/types";
// 导入本地存储工具类
import { Session, Local} from '@/utils/storage';
// 导入全局状态管理
// import useMyStore from '@/stores/states';

const router = useRouter();
// 使用登录 API 方法
// const useLoginApi = UseLoginApi()
// // 使用全局状态管理
// const useUserInfoStore = useMyStore()

// 记住密码，true 或 false
const rem_pswd = ref(Local.get('rem_pswd'))
const ruleFormRef = ref<FormInstance>();
// 生成随机验证码
const generateCode = () => {
    const code = ref('');
    const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
    for (let i = 0; i < 4; i++) {
        code.value += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return code.value;
}

// 传递验证码给子组件
const identifyCode = ref(generateCode())
// 刷新验证码
const refresh = () => {
    identifyCode.value = generateCode()
}
// 定义组件的响应式状态
interface State {
    loading: boolean;
    formData: LoginState;
}
const state: State = reactive({
    loading: false,
    formData: {
        username: "wmin",
        password: "123456",
        code: identifyCode.value,
    },
})
// 定义登录逻辑
const login = (data: LoginState) => {
    state.loading = true;
    setTimeout(() => {
        state.loading = false;
    }, 3000);
    if (state.formData.username === "wmin" && state.formData.password === "123456") {
        router.push("/");
    } else {
        alert("账号或密码错误");
        // ElMessage.error('账号或密码错误');
    }
    // const res = UseLoginApi().login(data)
    // // 登录成功后的处理逻辑
    // Session.set('token', res.data.token || '')
    // Session.set('username', res.data.userInfo.user || '')
    Session.set('token', 'token:123456')
    Session.set('username', 'wmin')
    // useMyStore().setUserInfo(res.data.userInfo || {username: 'wmin', password: '123456'})
    // useMyStore().setIsLogin(true)
    router.push('/')
}

const validateUserName = (rule: any, value: any, callback: any) => {
    if (value === "") {
        callback(new Error("请输入用户名"));
    } else {
        callback();
    }
};
const validatePassword = (rule: any, value: any, callback: any) => {
    if (value === "") {
        callback(new Error("请输入密码"));
    } else {
        callback();
    }
};
// 检测输入的验证码，
const checkCodeFun = (rule: any, value: any, callback: any) => {
    if (value === "") {
        callback(new Error("请输入验证码"));
    }
    else if ((value as string).toUpperCase() === identifyCode.value) {
        callback();
    } else {
        callback(new Error("验证码错误"));
    }
}

const formRules = reactive<FormRules<typeof state.formData>>({
    username: [{ validator: validateUserName, trigger: "blur" }],
    password: [{ validator: validatePassword, trigger: "blur" }],
    code: [{ validator: checkCodeFun, trigger: 'blur' }],
});

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid: any, fields: any) => {
        if (valid) {
            // 表单验证通过，执行登录逻辑
            let data: LoginState = {
                username: state.formData.username,
                password: state.formData.password,
                code: state.formData.code
            }
            login(data)
        } else {
            console.log("error submit!");
            return false;
        }
    });
};



</script>
<style lang="scss" scoped>
.system-title {
    text-align: left;
    font-size: 36px;
    font-weight: bolder;
    line-height: 100px;
    padding: 0px 40px;
}

.login-content {
    width: 500px;
    padding: 50px;
    background-color: #fff;
    border-radius: 10px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    .login-title {
        text-align: center;
        margin-bottom: 30px;

        h2 {
            font-size: 24px;
            font-weight: bolder;
        }
    }
    .btn-content{
        width:100%;
        display: flex;
        align-items: center;
        .labelText{
            flex: 1;
            text-align: left
        }
        .btn{
            flex:1;
            text-align: right
        }
    }
}
</style>
